import "./index.less";
import { View, Button } from "@tarojs/components";
import { useState } from "react";
import RadioText from "../RadioText";
import { NumberEditorProps } from "@/types";

const NumberEditor = ({
  label,
  initValue,
  onConfirm,
  unitOptions = [],
}: NumberEditorProps) => {
  const [value, setValue] = useState(initValue);
  const [unit, setUnit] = useState<number>(unitOptions[0]?.value || 1);

  // 处理数字输入
  const handleNumberInput = (num) => {
    // 当值为0时，点击其他数字替换0
    if (value === "0") {
      setValue(num);
    } else {
      setValue(value + num);
    }
  };

  // 清空
  const handleClear = () => {
    setValue("0");
  };

  // 回退
  const handleBackspace = () => {
    if (value.length === 1) {
      setValue("0");
    } else {
      setValue(value.slice(0, -1));
    }
  };

  // 确定
  const handleConfirm = () => {
    if (onConfirm) {
      if (unitOptions && unit) {
        onConfirm(Number(value) * unit);
      } else {
        onConfirm(Number(value));
      }
    }
  };
  return (
    <View className="number-editor">
      <View className="display-area">
        <View className="flex-center">
          <View className="display-label">{label}</View>
          <View className="display-value">{value}</View>
          {unitOptions.length > 1 && (
            <View className="display-unit">
              <RadioText
                options={unitOptions}
                value={unit}
                onChange={(v) => setUnit(Number(v))}
              />
            </View>
          )}
        </View>
        <Button className="function-btn confirm" onClick={handleConfirm}>
          确定
        </Button>
      </View>

      {/* 键盘区域 */}
      <View className="keyboard">
        {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((num) => (
          <Button
            key={num}
            className="number-btn"
            onClick={() => handleNumberInput(num.toString())}
          >
            {num}
          </Button>
        ))}

        <Button className="function-btn clear" onClick={handleClear}>
          清空
        </Button>

        <Button
          className="number-btn zero"
          onClick={() => handleNumberInput("0")}
        >
          0
        </Button>

        <Button className="function-btn backspace" onClick={handleBackspace}>
          ←
        </Button>
      </View>
    </View>
  );
};

export default NumberEditor;
